const db = require('../config/db');

class Product {
  static async getAll() {
    try {
      const [rows] = await db.query('SELECT * FROM products');
      return rows;
    } catch (error) {
 {
      throw error; // 或根据需要进行错误处理
    }
  }
  }
  static async getById(productId) {
    try {
      const [rows] = await db.query('SELECT * FROM products WHERE id = ?', [productId]);
      if (rows.length === 0) {
        throw { kind: 'not_found' };
      }
      return rows[0];
    } catch (error) {
      throw error;
    }
  }

  static async add(product) {
    try {
      if (!product.name || !product.price || !product.description) {
        throw new Error('缺少必需的产品信息（name, price, description）');
      }
      const [result] = await db.query('INSERT INTO products SET ?', product);
      product.id = result.insertId;
      return product;
    } catch (error) {
      throw error;
    }
  }

  static async update(id, updates) {
    try {
      await db.query('UPDATE products SET ? WHERE id = ?', [updates, id]);
      return { id, ...updates };
    } catch (error) {
      throw error;
    }
  }

  static async delete(id) {
    try {
      await db.query('DELETE FROM products WHERE id = ?', [id]);
    } catch (error) {
      throw error;
    }
  }
}

module.exports = Product;